package com.project.easy.common.framework.web.controller;

import com.project.easy.common.framework.auth.core.LoginProcessor;
import com.project.easy.common.framework.auth.dto.ReqLoginDto;
import com.project.easy.common.framework.auth.dto.TokenContext;
import com.project.easy.common.framework.captcha.core.CaptchaProcessor;
import com.project.easy.common.framework.web.service.impl.login.LoginProcessorProcessor;
import com.project.easy.common.log.annotation.Logging;
import  com.project.easy.common.util.constants.SysModelConstant;
import  com.project.easy.common.util.constants.VersionConstant;
import  com.project.easy.common.util.dto.CommonContextParam;
import  com.project.easy.common.util.dto.R;
import  com.project.easy.common.util.dto.UserInfo;
import  com.project.easy.common.util.exception.business.ParamRequireException;
import com.project.easy.common.framework.web.annotation.ApiValidator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author GreatorMan.cool
 * @copyright: Copyright (c) 2020
 * @company: 扬起科技有限公司
 * @date 2021/11/24 22:05
 * @description:
 */
@ConditionalOnBean(LoginProcessorProcessor.class)
@RestController
@RequestMapping("/api/" + VersionConstant.ONE + "/zysoft/user")
public class LoginController extends BaseController {
    /**
     * 验证码
     */
    @Autowired
    private LoginProcessor loginProcessor;

    @Autowired
    private CaptchaProcessor captchaProcessor;

    /**
     * 登陆接口
     * @param reqLoginDto 登陆参数
     * @return 返回登陆后信息
     */
    @PostMapping(value = "/login")
    public R<TokenContext> login(@RequestBody ReqLoginDto reqLoginDto) {
        Boolean validata = this.captchaProcessor.validata(reqLoginDto.getCaptchaKey(), reqLoginDto.getVerifyCode());
        if (!validata) {
            throw new ParamRequireException("验证编码非法或为空");
        }
        TokenContext login = loginProcessor.login(reqLoginDto);
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(login.getUserInfo(), userInfo);
        userInfo.setPassword("");
        login.setUserInfo(userInfo);
        //直接返回数据
        return R.success(login);
    }
    /**
     * 登出接口
     * @param contextParam 公共参数
     * @return 返回True成功
     */
    @PostMapping(value = "/logout")
    @Logging(value = SysModelConstant.USER_LOGINOUT)
    @ApiValidator(hasAuth = false)
    public R<Boolean> logout(@RequestBody CommonContextParam contextParam) {
        return R.success(loginProcessor.loginOut(contextParam));
    }
}
